<?php

require_once("../db/db.php");

class Collection {
	
	public function addCollection($name, $description, $tagIds, $contentIds) {
		
		$db = new Database();
		
		$collectionId = $db->getMax("collection", "id", true) + 1;
		
		// Add content to database
		$db->executeQuery("INSERT INTO collection(id, name, description) VALUES('" . $collectionId . "', '" . $name . "', '" . $description . "');");
				
		// Insert tags
		foreach($tagIds as $tag) {
			$collection_tag_id = $db->getMax("collection_tag", "id", true) + 1;
			$db->executeQuery("INSERT INTO collection_tag(id, collection_id, tag_id) VALUES ('" . $collection_tag_id . "','" . $collectionId . "','" . $tag . "');");
		}
			
		// Insert content
		foreach($contentIds as $content) {
			$collection_content_id = $db->getMax("collection_content", "id", true) + 1;
			$db->executeQuery("INSERT INTO collection_content(id, collection_id, content_id) VALUES ('" . $collection_content_id . "', '" . $collectionId . "','" . $content ."');");
		}
	}
	
	public function allCollections() {
		$db = new Database();
		
		$result = $db->executeQuery("SELECT * FROM collection");
		$result = $db->parseIntegers($result, "id");
		
		return $result;
	}
	
	public function getCollection($id) {
		
		$return = array();
		$db = new Database();
		
		// Get collection
		$result = $db->executeQuery("SELECT * FROM collection WHERE id='" . $id . "';");
		$result = $db->parseIntegers($result, "id");
		
		if ($result) {
			// Get row
			$collection = $result[0];
			
			$return["info"] = $collection;
			
			// All tags for collection
			$tagIdArray = $db->executeQuery("SELECT tag_id FROM collection_tag WHERE collection_id='" . $collection["id"] . "'");
			$tagIdArray = $db->parseIntegers($tagIdArray, "tag_id");
			
			$tags = array();
			foreach ($tagIdArray as $array) {
				$tagId = $array["tag_id"];
				$tagInfo = $db->executeQuery("SELECT * FROM tag WHERE id = " . $tagId);
				$tagInfo = $db->parseIntegers($tagInfo, "id");
				$tags[] = $tagInfo[0];
			}
			$return["tags"]= $tags;
			
			// All content for collection
			$contenIdArray = $db->executeQuery("SELECT content_id FROM collection_content WHERE collection_id='" . $collection["id"] . "'");
			$contenIdArray = $db->parseIntegers($contenIdArray, "content_id");
			
			$content = array();
			foreach ($contenIdArray as $array) {
				$contentId = $array["content_id"];
				$contentInfo = $db->executeQuery("SELECT * FROM content WHERE id = " . $contentId);
				$contentInfo = $db->parseIntegers($contentInfo, "id");
				$contentInfo = $db->parseIntegers($contentInfo, "id_zbirke");
				$content[] = $contentInfo[0];
			}
			$return["content"]= $content;
		}
		
		return $return;
	}
}

?>